package com.wangjie.simple;

/**
 * @author jieshao
 * @date 2022/5/13 16:29
 *
 * 9. 回文数
 */
public class Test02 {
    public static void main(String[] args) {
        int num = 1234321;
        boolean res1 = isPalindrome1(num);
        boolean res2 = isPalindrome2(num);
        System.out.println(res1);
        System.out.println(res2);
    }

    public static boolean isPalindrome1(int x) {
        if (x < 0) {
            return false;
        }
        int reverse = reverse(x);
        return x == reverse;
    }

    public static boolean isPalindrome2(int x) {
        // 当 x < 0 时，x 不是回文数，如果数字的最后一位是 0，为了使该数字为回文，则其第一位数字也应该是 0，只有 0 满足这一属性
        if (x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }

        int reverse = 0;
        while (x > reverse) {
            reverse = reverse * 10 + x % 10;
            x /= 10;
        }
        // 当数字长度为奇数时，我们可以通过 reverse / 10 去除处于中位的数字
        return x == reverse || x == reverse / 10;
    }

    /**
     * 数字反转
     *
     * @param num
     * @return
     */
    public static int reverse(int num) {
        int res = 0;
        while (num != 0) {
            res = res * 10 + num % 10;
            num = num / 10;
        }
        return res;
    }
}